using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.BomCommand;
using ClosedXML.Excel;
using System.IO;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile; // ImportResultDto

namespace RBAC.Write.Api.Controllers.WmzBom
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BomController : ControllerBase
    {
        private readonly IMediator mediator;

        public BomController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        #region 产品

        /// <summary>
        /// 新增产品
        /// </summary>
        /// <param name="request">产品新增命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回新增的产品Id</returns>
        [HttpPost]
        public async Task<APIResult<int>> ProductAdd([FromBody] ProductAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "新增产品异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 编辑产品（支持修改：名称、规格、描述）
        /// </summary>
        /// <param name="request">产品编辑命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> ProductUpdate([FromBody] ProductUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "编辑产品异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 逻辑删除产品（并逻辑删除关联数据）
        /// </summary>
        /// <param name="request">产品逻辑删除命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> ProductDelete([FromBody] ProductDeleteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "删除产品异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 下载产品导入模板
        /// </summary>
        /// <returns>Excel模板文件</returns>
        [HttpGet]
        public IActionResult DownloadProductImportTemplate()
        {
            try
            {
                using var workbook = new XLWorkbook();
                var worksheet = workbook.Worksheets.Add("产品导入模板");

                // 表头（与 `RBAC.Domain.BomManage.Product` 字段对应，去掉产品编码）
                var headers = new[]
                {
                    "产品名称（必填）",
                    "型号/规格",
                    "描述"
                };

                for (int i = 0; i < headers.Length; i++)
                {
                    worksheet.Cell(1, i + 1).Value = headers[i];
                    worksheet.Cell(1, i + 1).Style.Font.Bold = true;
                    worksheet.Cell(1, i + 1).Style.Fill.BackgroundColor = XLColor.LightGray;
                    if (i == 0)
                    {
                        // 必填列高亮为红色
                        worksheet.Cell(1, i + 1).Style.Font.FontColor = XLColor.Red;
                    }
                }

                // 示例数据行（无产品编码列）
                worksheet.Cell(2, 1).Value = "示例产品A";       // 产品名称
                worksheet.Cell(2, 2).Value = "型号X-100";     // 型号/规格
                worksheet.Cell(2, 3).Value = "这是一个示例产品"; // 描述

                worksheet.Columns().AdjustToContents();

                using var stream = new MemoryStream();
                workbook.SaveAs(stream);
                var bytes = stream.ToArray();

                return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "产品导入模板.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest("生成导入模板失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 产品导入（配合下载模板）
        /// </summary>
        /// <param name="file">Excel 文件</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>导入结果</returns>
        [HttpPost]
        public async Task<APIResult<ImportResultDto>> ProductImport(IFormFile file, CancellationToken cancellationToken)
        {
            try
            {
                var cmd = new ProductImportCommand { File = file };
                return await mediator.Send(cmd, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<ImportResultDto> { Code = APIEnums.Fail, Msg = "请求已取消", Data = new ImportResultDto() };
            }
            catch (Exception ex)
            {
                return new APIResult<ImportResultDto> { Code = APIEnums.Fail, Msg = "产品导入异常: " + ex.Message, Data = new ImportResultDto() };
            }
        }

        #endregion

        #region Bom

        /// <summary>
        /// 新增BOM
        /// </summary>
        /// <param name="request">BOM新增命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回新增的BOM Id</returns>
        [HttpPost]
        public async Task<APIResult<int>> BomAdd([FromBody] BomAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "新增BOM异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 编辑BOM（仅支持修改名称、版本、单位、修订说明、状态）
        /// </summary>
        /// <param name="request">BOM编辑命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> BomUpdate([FromBody] BomUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "编辑BOM异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 逻辑删除BOM（同时逻辑删除关联的明细BomItem，带事务）
        /// </summary>
        /// <param name="request">BOM逻辑删除命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> BomDelete([FromBody] BomDeleteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "删除BOM异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 下载BOM导入模板（仅主表，不含明细）
        /// </summary>
        /// <returns>Excel模板文件</returns>
        [HttpGet]
        public IActionResult DownloadBomImportTemplate()
        {
            try
    {
        using var workbook = new XLWorkbook();

        // 工作表：仅BOM主表
        var wsBom = workbook.Worksheets.Add("BOM主表");
        var bomHeaders = new[]
        {
            "BOM名称（必填）",
            "产品编码（必填）",
            "版本号（可选，默认V1.0）",
            "主单位（可选）",
            "修订说明（可选）"
        };
        for (int i = 0; i < bomHeaders.Length; i++)
        {
            wsBom.Cell(1, i + 1).Value = bomHeaders[i];
            wsBom.Cell(1, i + 1).Style.Font.Bold = true;
            wsBom.Cell(1, i + 1).Style.Fill.BackgroundColor = XLColor.LightGray;
        }
        // 标记必填列字体为红色
        wsBom.Cell(1, 1).Style.Font.FontColor = XLColor.Red; // BOM名称
        wsBom.Cell(1, 2).Style.Font.FontColor = XLColor.Red; // 产品编码
        // 示例行
        wsBom.Cell(2, 1).Value = "示例BOM-A";
        wsBom.Cell(2, 2).Value = "PRD-1001"; // 产品编码 示例
        wsBom.Cell(2, 3).Value = "V1.0";
        wsBom.Cell(2, 4).Value = "PCS";
        wsBom.Cell(2, 5).Value = "首次创建";
        wsBom.Columns().AdjustToContents();

        using var stream = new MemoryStream();
        workbook.SaveAs(stream);
        var bytes = stream.ToArray();

        return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "BOM导入模板（仅主表）.xlsx");
    }
    catch (Exception ex)
    {
        return BadRequest("生成BOM导入模板失败：" + ex.Message);
    }
        }
        
        /// <summary>
        /// BOM主表导入（字符串解析，支持 JSON 数组或带表头 CSV 文本）
        /// </summary>
        /// <param name="request">包含 Content 文本内容的导入命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>导入结果</returns>
        [HttpPost]
        public async Task<IActionResult> BomImport([FromBody] BomImportCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = await mediator.Send(request, cancellationToken);
                // 规则：只要有一条失败就返回 500
                if (res.Code == APIEnums.Fail || (res.Data != null && res.Data.FailCount > 0))
                {
                    return StatusCode(StatusCodes.Status500InternalServerError, res);
                }
                return Ok(res);
            }
            catch (OperationCanceledException)
            {
                var fail = new APIResult<ImportResultDto> { Code = APIEnums.Fail, Msg = "请求已取消", Data = new ImportResultDto() };
                return StatusCode(StatusCodes.Status500InternalServerError, fail);
            }
            catch (Exception ex)
            {
                var fail = new APIResult<ImportResultDto> { Code = APIEnums.Fail, Msg = "BOM导入异常: " + ex.Message, Data = new ImportResultDto() };
                return StatusCode(StatusCodes.Status500InternalServerError, fail);
            }
        }

        #endregion

        #region BomItem
        /// <summary>
        /// 新增BOM明细
        /// </summary>
        /// <param name="request">BOM明细新增命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回新增的明细Id</returns>
        [HttpPost]
        public async Task<APIResult<int>> BomItemAdd([FromBody] BomItemAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "新增BOM明细异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 编辑BOM明细
        /// </summary>
        /// <param name="request">BOM明细编辑命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> BomItemUpdate([FromBody] BomItemUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "编辑BOM明细异常: " + ex.Message, Data = 0 };
            }
        }

        /// <summary>
        /// 逻辑删除BOM明细（仅单个，含级联删除其所有子节点）
        /// </summary>
        /// <param name="request">BOM明细删除命令（仅需提供 Id）</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> BomItemDelete([FromBody] BomItemDeleteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "请求已取消", Data = 0 };
            }
            catch (Exception ex)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "删除BOM明细异常: " + ex.Message, Data = 0 };
            }
        }

        #endregion
    }
}
